﻿using sixgod.Common.Model;

namespace sixgod.Common.Helper;

public class UserContext
{
    private static readonly AsyncLocal<UserContext> _asyncLocal = new AsyncLocal<UserContext>();
    public static UserContext Current => _asyncLocal.Value;

    /// <summary>
    /// 登录用户信息
    /// </summary>
    public LoginInfo UserToken { get; set; } = new LoginInfo();

    /// <summary>
    /// 将请求上下文设置到线程全局区域
    /// </summary>
    /// <param name="userContext"></param>
    public static IDisposable SetContext(UserContext userContext)
    {
        _asyncLocal.Value = userContext;
        return new UserContextDisposable();
    }

    /// <summary>
    /// 清除上下文
    /// </summary>
    public static void ClearContext()
    {
        _asyncLocal.Value = null;
    }
}

/// <summary>
/// 用于释放对象
/// </summary>
internal class UserContextDisposable : IDisposable
{
    public void Dispose()
    {
        UserContext.ClearContext();
    }
}